"use strict";

import Vue from 'vue';
import axios from "axios";
import vuexStore from '../store/index';
import { Toast } from 'vant';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    // baseURL: "https://apis.netstart.cn/maoyan/" || "http://120.78.9.102:8006/api" || ""
    baseURL: "https://apis.netstart.cn/maoyan/" || ""
        // baseURL: "http://120.78.9.102:8003/api/"
        // baseURL: process.env.baseURL || process.env.apiUrl || ""
        // timeout: 60 * 1000, // Timeout
        // withCredentials: true, // Check cross-site Access-Control
};

// console.log(config);


const _axios = axios.create(config);
//请求前拦截器
_axios.interceptors.request.use(
    function(config) {
        // Do something before request is sent
        if (vuexStore.getters.loginToken) {
            config.headers = {
                "authorization": "Bearer " + vuexStore.getters.loginToken
            }
        }
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
          });
        return config;
    },
    function(error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function(response) {
        //响应拦截
        // console.log('---->', response);
        if (response.data) {
            if (response.data.data) {
                return response.data.data;
            }
            return response.data;
        }
        Toast.clear()
        // Do something with response data
        return response;
    },
    function(error) {
        Toast.clear()
        // Do something with response error
        return Promise.reject(error);
    }
);

Plugin.install = function(Vue, options) {
    Vue.axios = _axios;
    window.axios = _axios;
    Object.defineProperties(Vue.prototype, {
        axios: {
            get() {
                return _axios;
            }
        },
        $axios: {
            get() {
                return _axios;
            }
        },
    });
};

Vue.use(Plugin)

export default _axios;